package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.BompTreeNodeConstant;
import cc.rengu.igas.bomp.common.constant.TableNameConstant;
import cc.rengu.igas.bomp.common.dao.BizHistoryMapper;
import cc.rengu.igas.bomp.common.dao.BizTmpMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntSignInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.BizHistoryMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BizTmpMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntSignInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.*;
import cc.rengu.igas.bomp.common.util.ChangeNextStatusUtil;
import cc.rengu.igas.bomp.common.util.CompareFieldsUtil;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.model.UserSessionInfo;
import cc.rengu.igas.bomp.core.realize.MchntVerifyService;
import cc.rengu.igas.bomp.core.realize.impl.MchntVerifyServiceImpl;
import cc.rengu.igas.bomp.core.service.base.AuditService;
import cc.rengu.igas.bomp.facade.bean.*;
import cc.rengu.igas.bomp.facade.enums.BompManageOprTypeEnum;
import cc.rengu.igas.bomp.facade.enums.BompMchntStatusEnum;
import cc.rengu.igas.bomp.facade.request.MchntSignInfoManageRequest;
import cc.rengu.igas.bomp.facade.response.MchntSignInfoManageResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhangxuran
 * @Date: 2020/3/30 20:46
 * @Description: 商户签约信息管理
 * 新增签约信息
 * 1、根据机构号，商户号查询商户基础信息是否存在且商户状态不能为注销
 * 2、校验法人最大签约限制
 * 3、校验执照最大签约限制
 * 4、初始化商户签约信息
 * 5、数据存入商户签约信息表，商户映像信息表，业务信息表，
 */
public class MchntSignInfoManageService extends AuditService {

    private boolean NO_MODIFY_FLAG = true;

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntSignInfoManageRequest request = new MchntSignInfoManageRequest();
        ConvertUtil.convertOutput(request);

        if (!BompManageOprTypeEnum.isBompManageOprTypeByType(request.getOprType())) {
            rglog.error("商户签约信息管理失败！操作类型不符合规定！传入instId:{},前端流水号:{}，oprType:{}."
                    , request.getHeader().getInstId(), request.getHeader().getTraceNo(), request.getOprType());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                    RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        //审核时参数校验
        if (BompManageOprTypeEnum.AUDIT.getType().equals(request.getOprType())) {

            rglog.error("商户签约信息管理失败！不允许进行审核！传入instId:{},前端流水号:{}."
                    , request.getHeader().getInstId(), request.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                    RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        BusinessLicenceInfoBean businessLicenceInfoBean = request.getBusinessLicenceInfoBean();
        MchntArtifInfoBean mchntArtifInfoBean = request.getMchntArtifInfoBean();
        if (null == businessLicenceInfoBean
                || null == mchntArtifInfoBean
                || null == mchntArtifInfoBean.getCertBackImage()
                || null == mchntArtifInfoBean.getCertFaceImage()) {
            rglog.error("必填项为空！不允许进行签约管理！！传入instId:{},前端流水号:{}",
                    request.getHeader().getInstId(), request.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
        }

        return request;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntSignInfoManageRequest mchntSignInfoManageRequest = (MchntSignInfoManageRequest) request;
        BizResponse<MchntSignInfoManageResponse> bizResponse = new BizResponse<>();
        MchntSignInfoManageResponse mchntSignInfoManageResponse = new MchntSignInfoManageResponse();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = mchntSignInfoManageRequest.getHeader().getInstId();
        String mchntNo = mchntSignInfoManageRequest.getMchntNo();

        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        //查询商户信息
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(
                mchntSignInfoManageRequest.getHeader().getInstId(), mchntSignInfoManageRequest.getMchntNo());
        if (null == mchntBaseInfo) {
            rglog.error("管理商户签约信息失败, 根据商户号查询商户基本信息为空，instId:{},mchntNo:{}",
                    mchntSignInfoManageRequest.getHeader().getInstId(), mchntSignInfoManageRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }

        if (BompMchntStatusEnum.CANCEL.getType().equals(mchntBaseInfo.getMchntStatus())) {
            rglog.error("管理商户签约信息失败, 根据商户号查询商户状态为已注销，instId:{},mchntNo:{}", mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_CANCEL.getRespCode(), RespCodeEnum.MCHNT_CANCEL.getRespDesc());
        }

        //商户签约信息
        MchntArtifInfoBean mchntArtifInfoBean = mchntSignInfoManageRequest.getMchntArtifInfoBean();
        BusinessLicenceInfoBean businessLicenceInfoBean = mchntSignInfoManageRequest.getBusinessLicenceInfoBean();

        String channelId = mchntSignInfoManageRequest.getHeader().getChanlId();
        if ("WECHAT".equals(channelId) || "MOBILE".equals(channelId) || "APP".equals(channelId) || "PCWEB".equals(channelId)) {
            //解密敏感信息
            String sessionObjStr = RedisUtil.onceGet(mchntSignInfoManageRequest.getHeader().getSession());
            UserSessionInfo userSessionInfo = JSON.parseObject(sessionObjStr, UserSessionInfo.class);
            mchntArtifInfoBean.setArtifCertNo(descriptData(userSessionInfo.getSensitiveKey(), mchntArtifInfoBean.getArtifCertNo()));
            mchntArtifInfoBean.setArtifMobile(descriptData(userSessionInfo.getSensitiveKey(), mchntArtifInfoBean.getArtifMobile()));
            mchntSignInfoManageRequest.setMchntArtifInfoBean(mchntArtifInfoBean);

            if (!StringUtil.isEmptyOrNull(businessLicenceInfoBean.getLicenceCode())) {
                businessLicenceInfoBean.setLicenceCode(descriptData(userSessionInfo.getSensitiveKey(), businessLicenceInfoBean.getLicenceCode()));
                mchntSignInfoManageRequest.setBusinessLicenceInfoBean(businessLicenceInfoBean);
            }
        }

        SysParamMapper sysParamMapper = new SysParamMapperImpl();
        MchntVerifyService mchntVerifyService = new MchntVerifyServiceImpl();

        /*特色化需求:六要素校验*/
        SysParam sixCheckSysParam = sysParamMapper.selectSysParamByPrimaryKey(instId, BompAppParamConstant.MCHNT_PARAM_TYPE, BompAppParamConstant.SIX_CHECK_FLAG);
        if (null != sixCheckSysParam && "Y".equals(sixCheckSysParam.getParamValue())) {
            String licenceType = mchntSignInfoManageRequest.getBusinessLicenceInfoBean().getLicenceType();
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.LICENCE_TYPE, licenceType);
            String licenceCode = mchntSignInfoManageRequest.getBusinessLicenceInfoBean().getLicenceCode();
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.LICENCE_CODE, licenceCode);
            String certType = mchntSignInfoManageRequest.getMchntArtifInfoBean().getArtifCertType();
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.CERT_TYPE, certType);
            String certNo = mchntSignInfoManageRequest.getMchntArtifInfoBean().getArtifCertNo();
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.CERT_NO, certNo);
            String mobile = mchntSignInfoManageRequest.getMchntArtifInfoBean().getArtifMobile();
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.MOBILE, mobile);
            //操作类型入参:01-新增/02-修改/03-审核
            String sixCheckOprType = mchntSignInfoManageRequest.getOprType() + "1";// 011/021
            if (!mchntVerifyService.verifySixElement(instId, mchntNo, sixCheckOprType)) {
                rglog.error("六要素校验不通过.");
                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
            }
        }

        /*特色化需求:校验线下商户签约信息是否重复*/
        SysParam offlineLicenceSysParam = sysParamMapper.selectSysParamByPrimaryKey(instId, BompAppParamConstant.MCHNT_PARAM_TYPE, BompAppParamConstant.OFFLINE_LICENCE_CHECK_FLAG);
        if (BompManageOprTypeEnum.CREATE.getType().equals(mchntSignInfoManageRequest.getOprType())) {
            //营业执照时校验  营业执照最大签约数
            if ("00".equals(businessLicenceInfoBean.getLicenceType())) {
                /*特色化处理：判断是否校验商户签约信息*/
                if (null != offlineLicenceSysParam && "Y".equals(offlineLicenceSysParam.getParamValue()) && MchntAttrEnum.ONLINE_MCHNT.getMchntAttrCode().equals(mchntBaseInfo.getMchntAttr())) {
                    //线上线下商户按线下商户处理,进行校验
                    rglog.debug("特色化处理,所配置线上商户不校验营业执照签约商户个数,机构号<{}>", instId);
                } else {
                    //非特色化普通校验
                    mchntVerifyService.verifyLicenceMaxByMchntSign(instId, mchntNo, businessLicenceInfoBean.getLicenceType(), businessLicenceInfoBean.getLicenceCode());
                }
            }

            if (mchntVerifyService.checkMchntBlackInfoByLegalInfo(mchntArtifInfoBean.getArtifCertType(), mchntArtifInfoBean.getArtifCertNo())) {
                rglog.error("商户签约信息管理-新增商户失败！法人证件黑名单校验失败！instId:{},mchntNo:{},ArtifCertNo:{}."
                        , instId, mchntNo, mchntArtifInfoBean.getArtifCertNo());
                throw new BizException(RespCodeEnum.BLACK_LIST_LEGAL_INFO.getRespCode(), RespCodeEnum.BLACK_LIST_LEGAL_INFO.getRespDesc());
            }


            if (mchntVerifyService.checkMchntBlackInfoByLicenceCode(businessLicenceInfoBean.getLicenceCode())) {
                rglog.error("商户签约信息管理-新增商户失败！商户证件黑名单校验失败！instId:{},mchntNo:{},LicenceCode:{}."
                        , instId, mchntNo, businessLicenceInfoBean.getLicenceCode());
                throw new BizException(RespCodeEnum.BLACK_LIST_LICENCE_CODE.getRespCode(), RespCodeEnum.BLACK_LIST_LICENCE_CODE.getRespDesc());
            }

            increaseMchntSignInfo(mchntSignInfoManageRequest, xmlTreeUtil, mchntBaseInfo);
        } else if (BompManageOprTypeEnum.MODIFY.getType().equals(mchntSignInfoManageRequest.getOprType())) {
            if ("00".equals(businessLicenceInfoBean.getLicenceType())) {
                //营业执照时校验  营业执照最大签约数

                /*特色化处理：判断是否校验商户签约信息*/
                if (null != offlineLicenceSysParam && "Y".equals(offlineLicenceSysParam.getParamValue()) && MchntAttrEnum.ONLINE_MCHNT.getMchntAttrCode().equals(mchntBaseInfo.getMchntAttr())) {
                    //线上线下商户按线下商户处理,进行校验
                    rglog.debug("特色化处理,线上商户不校验营业执照签约商户个数.");
                } else {
                    //非特色化普通校验
                    mchntVerifyService.verifyLicenceMaxByMchntSign(instId, mchntNo, businessLicenceInfoBean.getLicenceType(), businessLicenceInfoBean.getLicenceCode());
                }
            }

            if (AuditStatusEnum.BE_AUDIT.getAuditStatus().equals(mchntBaseInfo.getAuditStatus())) {
                if (mchntVerifyService.checkMchntBlackInfoByLegalInfo(mchntArtifInfoBean.getArtifCertType(), mchntArtifInfoBean.getArtifCertNo())) {
                    rglog.error("商户签约信息管理-新增商户失败！法人证件黑名单校验失败！instId:{},mchntNo:{},ArtifCertNo:{}."
                            , instId, mchntNo, mchntArtifInfoBean.getArtifCertNo());
                    throw new BizException(RespCodeEnum.BLACK_LIST_LEGAL_INFO.getRespCode(), RespCodeEnum.BLACK_LIST_LEGAL_INFO.getRespDesc());
                }


                if (mchntVerifyService.checkMchntBlackInfoByLicenceCode(businessLicenceInfoBean.getLicenceCode())) {
                    rglog.error("商户签约信息管理-新增商户失败！商户证件黑名单校验失败！instId:{},mchntNo:{},LicenceCode:{}."
                            , instId, mchntNo, businessLicenceInfoBean.getLicenceCode());
                    throw new BizException(RespCodeEnum.BLACK_LIST_LICENCE_CODE.getRespCode(), RespCodeEnum.BLACK_LIST_LICENCE_CODE.getRespDesc());
                }
            }
            //修改商户签约信息
            modifyMchntSignInfo(xmlTreeUtil, mchntSignInfoManageRequest, mchntBaseInfo);
        } else {
            //审核商户基本信息
            rglog.error("不允许单个页面进行审核操作！instId:{},前端流水号:{}",
                    mchntSignInfoManageRequest.getHeader().getInstId(), mchntSignInfoManageRequest.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        mchntSignInfoManageResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        mchntSignInfoManageResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntSignInfoManageResponse);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        return bizResponse;
    }

    private void increaseMchntSignInfo(MchntSignInfoManageRequest request,
                                       XmlTreeUtil xmlTreeUtil,
                                       MchntBaseInfo mchntBaseInfo) throws Exception {

        MchntSignInfo mchntSignInfo = InitParamUtil.initMchntSignInfoByCreate(request.getMchntArtifInfoBean(),
                request.getBusinessLicenceInfoBean(), mchntBaseInfo.getMchntNo(), request.getHeader().getInstId(), request.getUserId());
        List<BizTmp> bizTmpList = new ArrayList<>();
        BizTmp signBizTmp = convertBizTmpByMchntSignInfoByInsert(mchntBaseInfo, mchntSignInfo, request);
        bizTmpList.add(signBizTmp);

        createMchntSignInfoDb(request, xmlTreeUtil, mchntSignInfo, bizTmpList, null);

    }

    private BizTmp convertBizTmpByMchntImageInfoByInsert(MchntBaseInfo mchntBaseInfo, MchntImageInfo mchntImageInfo, MchntSignInfoManageRequest request) {
        BizTmp bizTmp = new BizTmp();
        BeanUtil.beanCopy(mchntBaseInfo, bizTmp);
        BeanUtil.beanCopy(mchntImageInfo, bizTmp);
        bizTmp.setManageInstId(mchntBaseInfo.getSignInstId());
        bizTmp.setMchntName(mchntBaseInfo.getMchntName());
        bizTmp.setRealId(mchntImageInfo.getId());
        bizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_IMAGE_INFO);
        //新增
        bizTmp.setBizOpr("I");
        bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
        bizTmp.setAuditStatus(AuditStatusEnum.BE_AUDIT.getAuditStatus());
        //明细记录
        bizTmp.setDetailFlag(BompAppParamConstant.FLAG_Y);
        bizTmp.setMasterShowFlag(BompAppParamConstant.FLAG_N);
        //填写商户基本信息的id作为key
        bizTmp.setMasterKey(mchntBaseInfo.getId());
        bizTmp.setMasterShowFlag(request.getMasterShowFlag());
        bizTmp.setOprMenuId(request.getOprMenuId());
        bizTmp.setOprMenuName(request.getOprMenuName());
        String mchntImageInfoJson = JSONObject.toJSONString(mchntImageInfo);
        InitParamUtil.initBizTempData(bizTmp, mchntImageInfoJson);
        return bizTmp;
    }

    private BizTmp convertBizTmpByMchntSignInfoByInsert(MchntBaseInfo mchntBaseInfo,
                                                        MchntSignInfo mchntSignInfo,
                                                        MchntSignInfoManageRequest request) throws Exception {
        BizTmp bizTmp = new BizTmp();
        ConvertUtil.convertOutput(bizTmp);
        BeanUtil.beanCopy(mchntBaseInfo, bizTmp);
        BeanUtil.beanCopy(mchntSignInfo, bizTmp);
        bizTmp.setMchntName(mchntBaseInfo.getMchntName());
        bizTmp.setManageInstId(mchntBaseInfo.getSignInstId());
        bizTmp.setRealId(mchntSignInfo.getId());
        bizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_SIGN_INFO);
        //新增
        bizTmp.setBizOpr("I");
        bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
        bizTmp.setAuditStatus(AuditStatusEnum.BE_AUDIT.getAuditStatus());
        bizTmp.setDetailFlag(BompAppParamConstant.FLAG_N);
        //签约信息为主记录
        bizTmp.setMasterShowFlag(request.getMasterShowFlag());
        bizTmp.setMasterKey(mchntBaseInfo.getId());
        String mchntSignInfoJson = JSONObject.toJSONString(mchntSignInfo);
        InitParamUtil.initBizTempData(bizTmp, mchntSignInfoJson);
        return bizTmp;
    }


    private void modifyMchntSignInfo(XmlTreeUtil xmlTreeUtil,
                                     MchntSignInfoManageRequest request,
                                     MchntBaseInfo mchntBaseInfo) throws Exception {
        String modifyTime = DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS);

        MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
        MchntSignInfo dbMchntSignInfo = mchntSignInfoMapper.selectMchntSignInfoByPrimaryKey(request.getHeader().getInstId(),
                request.getMchntNo());
        if (null == dbMchntSignInfo) {
            if (AuditStatusEnum.BE_AUDIT.getAuditStatus().equals(mchntBaseInfo.getAuditStatus())) {
                dbMchntSignInfo = InitParamUtil.initMchntSignInfoByCreate(request.getMchntArtifInfoBean(), request.getBusinessLicenceInfoBean(), mchntBaseInfo.getMchntNo(), mchntBaseInfo.getInstId(), request.getUserId());
            } else {
                rglog.error("修改商户签约信息失败, 根据商户号查询商户签约信息为空，instId:{},mchntNo:{}",
                        request.getHeader().getInstId(), request.getMchntNo());
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
        }

        //判断当前状态是否允许修改
        if (!ChangeNextStatusUtil.isAllowModifyData(dbMchntSignInfo.getAuditStatus())) {
            rglog.error("修改商户签约信息失败, 当前商户信息待审核，不允许修改，instId:{},mchntNo:{},当前商户审核状态:{}",
                    dbMchntSignInfo.getInstId(), dbMchntSignInfo.getMchntNo(), dbMchntSignInfo.getAuditStatus());
            throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
        }

        //默认修改待审核
        String auditStatus = AuditStatusEnum.MODIFY_BE_COMMIT_AUDIT.getAuditStatus();
        //默认临时表操作类型为修改
        String bizTmpBizOpr = "U";
        if (AuditStatusEnum.BE_AUDIT.getAuditStatus().equals(dbMchntSignInfo.getAuditStatus())
                || AuditStatusEnum.ADD_AUDIT_REJECT.getAuditStatus().equals(dbMchntSignInfo.getAuditStatus())) {
            //新增草稿状态修改或新增审核失败修改 -> 提交待审核
            modifySignByCreatProcessing(xmlTreeUtil, request, mchntBaseInfo, modifyTime, dbMchntSignInfo);
        } else if (AuditStatusEnum.MODIFY_BE_COMMIT_AUDIT.getAuditStatus().equals(dbMchntSignInfo.getAuditStatus())) {
            //当前状态为修改草稿，需从BizTmp中取数据进行修改
            BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
            BizTmp signBizTmp = bizTmpMapper.selectBizTmpByRealId(dbMchntSignInfo.getInstId(), dbMchntSignInfo.getId());
            MchntSignInfo modifyMchntSignInfo = JSON.parseObject(InitParamUtil.getJsonString(signBizTmp), MchntSignInfo.class);
            modifyMchntSignInfo = InitParamUtil.initMchntSignInfoByModify(request.getMchntArtifInfoBean(),
                    request.getBusinessLicenceInfoBean(), modifyMchntSignInfo, request.getUserId(), auditStatus);
            modifyMchntSignInfo.setLastUpdateTime(modifyTime);

            //原商户信息改为 修改待审核
            dbMchntSignInfo.setAuditStatus(auditStatus);
            dbMchntSignInfo.setLastOprId(request.getUserId());
            dbMchntSignInfo.setLastUpdateTime(modifyTime);

            List<BizTmp> bizTmpList = new ArrayList<>();
            BizTmp bizTmp = getBizTmpBySignInfoModify(mchntBaseInfo, dbMchntSignInfo, modifyMchntSignInfo, request, bizTmpBizOpr);
            bizTmpList.add(bizTmp);

            //忽略不进行对比的数据
            String[] ignore = new String[]{"auditStatus", "lastOprId", "lastUpdateTime"};
            String compareModify = CompareFieldsUtil.compareFields(dbMchntSignInfo, modifyMchntSignInfo, ignore);
            if (StringUtil.isEmptyOrNull(compareModify)) {
                compareModify = "没有修改签约数据";
                rglog.debug("签约信息管理-修改商户签约信息，与数据库信息对比，没有修改数据。");
            }


            // List<MchntImageInfo> dbMchntImageInfoList = getModifyImageList(request, mchntBaseInfo, modifyTime, auditStatus, bizTmpBizOpr, bizTmpList);
            //需要审核， 更新正式表的信息为修改待审核， 将传入的商户信息更新到业务临时表
            modifyMchntSignInfoDb(request, dbMchntSignInfo, bizTmpList, null);
        } else {

            //修改的信息
            MchntSignInfo modifyMchntSignInfo = InitParamUtil.initMchntSignInfoByModify(request.getMchntArtifInfoBean(),
                    request.getBusinessLicenceInfoBean(), dbMchntSignInfo, request.getUserId(), auditStatus);
            modifyMchntSignInfo.setLastUpdateTime(modifyTime);

            //不允许修改的数据
            //营业执照信息、法人信息不能修改。
            String[] errorArr = new String[]{"licenceType", "enterRegisterType", "licenceName",
                    "licenceCode", "licenceEffectiveDate", "licenceExpiryDate", "artifName",
                    "artifCertType", "artifCertNo"};

            String compareModifyError = CompareFieldsUtil.noAllowModifyFields(dbMchntSignInfo, modifyMchntSignInfo, errorArr);
            if (!StringUtil.isEmptyOrNull(compareModifyError)) {
                rglog.debug("商户基本信息管理-修改商户签约信息，与数据库信息对比，没有修改数据。");
            }

            //忽略不进行对比的数据
            String[] ignore = new String[]{"auditStatus", "lastOprId", "lastUpdateTime"};
            String compareModify = CompareFieldsUtil.compareFields(dbMchntSignInfo, modifyMchntSignInfo, ignore);
            if (StringUtil.isEmptyOrNull(compareModify)) {
                compareModify = "没有修改签约数据";
                rglog.debug("签约信息管理-修改商户签约信息，与数据库信息对比，没有修改数据。");
            }

            //原商户信息改为 修改待审核
            dbMchntSignInfo.setAuditStatus(auditStatus);
            dbMchntSignInfo.setLastOprId(request.getUserId());
            dbMchntSignInfo.setLastUpdateTime(modifyTime);

            List<BizTmp> bizTmpList = new ArrayList<>();
            BizTmp bizTmp = getBizTmpBySignInfoModify(mchntBaseInfo, dbMchntSignInfo, modifyMchntSignInfo, request, bizTmpBizOpr);
            bizTmpList.add(bizTmp);

            List<BizHistory> bizHistoryList = new ArrayList<>();
            BizHistory bizHistory = new BizHistory();
            BeanUtil.beanCopy(bizTmp, bizHistory);
            bizHistory.setCreateTime(dbMchntSignInfo.getLastUpdateTime());
            //将正式表的商户信息存入历史表 bizData
            InitParamUtil.initBizHistoryData(bizHistory, compareModify);
            bizHistoryList.add(bizHistory);

            //需要审核， 更新正式表的信息为修改待审核， 将传入的商户信息更新到业务临时表
            modifyMchntSignInfoDb(request, dbMchntSignInfo, bizTmpList, null);
        }


    }

    private void modifySignByCreatProcessing(XmlTreeUtil xmlTreeUtil, MchntSignInfoManageRequest request, MchntBaseInfo mchntBaseInfo, String modifyTime, MchntSignInfo dbMchntSignInfo) throws Exception {
        String auditStatus;
        String bizTmpBizOpr;//新增草稿状态修改或新增审核失败修改 -> 提交待审核
        rglog.debug("新增草稿状态修改或新增审核失败修改");
        auditStatus = AuditStatusEnum.BE_AUDIT.getAuditStatus();
        bizTmpBizOpr = "I";

        //修改的信息
        MchntSignInfo modifyMchntSignInfo = InitParamUtil.initMchntSignInfoByModify(request.getMchntArtifInfoBean(),
                request.getBusinessLicenceInfoBean(), dbMchntSignInfo, request.getUserId(), auditStatus);
        modifyMchntSignInfo.setLastUpdateTime(modifyTime);

        //不允许修改的数据
        //营业执照信息、法人信息不能修改。
        String[] errorArr = new String[]{"licenceType", "enterRegisterType", "licenceName",
                "licenceCode", "licenceEffectiveDate", "licenceExpiryDate", "artifName",
                "artifCertType", "artifCertNo"};

        String compareModifyError = CompareFieldsUtil.noAllowModifyFields(dbMchntSignInfo, modifyMchntSignInfo, errorArr);
        if (!StringUtil.isEmptyOrNull(compareModifyError)) {
            rglog.debug("商户基本信息管理-修改商户签约信息，与数据库信息对比，没有修改数据。");
        }

        //忽略不进行对比的数据
        String[] ignore = new String[]{"auditStatus", "lastOprId", "lastUpdateTime"};
        String compareModify = CompareFieldsUtil.compareFields(dbMchntSignInfo, modifyMchntSignInfo, ignore);
        if (StringUtil.isEmptyOrNull(compareModify)) {
            compareModify = "没有修改签约数据";
            rglog.debug("签约信息管理-修改 新增草稿或新增失败的商户签约信息，与数据库信息对比，没有修改数据。");
        }

        //原商户信息改为 修改待审核
        dbMchntSignInfo.setAuditStatus(auditStatus);
        dbMchntSignInfo.setLastOprId(request.getUserId());
        dbMchntSignInfo.setLastUpdateTime(modifyTime);

        List<BizTmp> bizTmpList = new ArrayList<>();
        BizTmp bizTmp = getBizTmpBySignInfoModify(mchntBaseInfo, dbMchntSignInfo, modifyMchntSignInfo, request, bizTmpBizOpr);
        bizTmpList.add(bizTmp);

        //需要审核， 更新正式表的信息为修改待审核， 将传入的商户信息更新到业务临时表
        modifyMchntSignInfoDb(request, modifyMchntSignInfo, bizTmpList, null);
    }

    private BizTmp getBizTmpBySignInfoModify(MchntBaseInfo mchntBaseInfo,
                                             MchntSignInfo dbMchntSignInfo,
                                             MchntSignInfo modifyMchntSignInfo,
                                             MchntSignInfoManageRequest request,
                                             String bizOprType) throws Exception {
        BizTmp bizTmp = new BizTmp();
        BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
        //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
        BizTmp oldBizTemp = bizTmpMapper.selectBizTmpByRealId(dbMchntSignInfo.getInstId(), dbMchntSignInfo.getId());
        if (null != oldBizTemp) {
            BeanUtil.beanCopy(oldBizTemp, bizTmp);
            ConvertUtil.convertOutput(bizTmp);
            BeanUtil.beanCopy(modifyMchntSignInfo, bizTmp);
            bizTmp.setDetailFlag(BompAppParamConstant.FLAG_Y);
        } else {
            ConvertUtil.convertOutput(bizTmp);
            BeanUtil.beanCopy(mchntBaseInfo, bizTmp);
            BeanUtil.beanCopy(modifyMchntSignInfo, bizTmp);
            bizTmp.setManageInstId(mchntBaseInfo.getSignInstId());
            bizTmp.setRealId(dbMchntSignInfo.getId());
            bizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_SIGN_INFO);
            bizTmp.setDetailFlag(BompAppParamConstant.FLAG_Y);
            bizTmp.setMasterShowFlag(BompAppParamConstant.FLAG_N);
            bizTmp.setMasterKey(mchntBaseInfo.getId());
        }
        bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
        //修改
        bizTmp.setBizOpr(bizOprType);
        //修改待审批
        bizTmp.setAuditStatus(modifyMchntSignInfo.getAuditStatus());
        bizTmp.setMasterShowFlag(request.getMasterShowFlag());
        String modifyMchntSignInfoJson = JSONObject.toJSONString(modifyMchntSignInfo);
        InitParamUtil.initBizTempData(bizTmp, modifyMchntSignInfoJson);
        return bizTmp;
    }

    /**
     * 新增商户基础信息
     */
    private void createMchntSignInfoDb(MchntSignInfoManageRequest request,
                                       XmlTreeUtil xmlTreeUtil,
                                       MchntSignInfo mchntSignInfo,
                                       List<BizTmp> bizTmpList,
                                       List<BizHistory> bizHistoryList) throws Exception {
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        try {

            MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
            int dbResult = mchntSignInfoMapper.insertMchntSignInfo(mchntSignInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("新增商户签约信息表失败！id:{},mchnt:{},instId:{}",
                        mchntSignInfo.getId(), mchntSignInfo.getMchntNo(), mchntSignInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            if (!CollectionUtils.isEmpty(bizTmpList)) {
                BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
                for (BizTmp bizTmp : bizTmpList) {
                    dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("新增商户签约信息-业务临时表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizTmp.getRealId(), bizTmp.getManageInstId(), bizTmp.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            if (!CollectionUtils.isEmpty(bizHistoryList)) {
                BizHistoryMapper bizHistoryMapper = new BizHistoryMapperImpl();
                for (BizHistory bizHistory : bizHistoryList) {
                    dbResult = bizHistoryMapper.insertBompBizHistory(bizHistory);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("新增商户签约信息-业务历史表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizHistory.getRealId(), bizHistory.getManageInstId(), bizHistory.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            //影像处理
            manageSignImageInfo(request);

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("商户签约管理失败！ e:{}", e.getMessage());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }


    private void modifyMchntSignInfoDb(MchntSignInfoManageRequest request,
                                       MchntSignInfo mchntSignInfo,
                                       List<BizTmp> bizTmpList,
                                       List<BizHistory> bizHistoryList) throws Exception {
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        try {
            MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
            int dbResult = mchntSignInfoMapper.updateMchntSignInfoById(mchntSignInfo);
            if (dbResult != 0) {
                dbResult = mchntSignInfoMapper.insertMchntSignInfo(mchntSignInfo);
                if (dbResult != 0) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("修改商户签约信息表失败！id:{},mchnt:{},instId:{}",
                            mchntSignInfo.getId(), mchntSignInfo.getMchntNo(), mchntSignInfo.getInstId());
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            }

            if (!CollectionUtils.isEmpty(bizTmpList)) {
                BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
                for (BizTmp bizTmp : bizTmpList) {
                    //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
                    BizTmp oldBizTemp = bizTmpMapper.selectBizTmpByRealId(bizTmp.getInstId(), bizTmp.getRealId());
                    if (null == oldBizTemp) {
                        dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                    } else {
                        dbResult = bizTmpMapper.updateBizTmpByRealId(bizTmp);
                    }
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("修改商户签约信息-临时表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizTmp.getRealId(), bizTmp.getManageInstId(), bizTmp.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            if (!CollectionUtils.isEmpty(bizHistoryList)) {
                BizHistoryMapper bizHistoryMapper = new BizHistoryMapperImpl();
                for (BizHistory bizHistory : bizHistoryList) {
                    dbResult = bizHistoryMapper.insertBompBizHistory(bizHistory);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("修改商户签约信息- 新增业务历史表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizHistory.getRealId(), bizHistory.getManageInstId(), bizHistory.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            //影像处理
            manageSignImageInfo(request);

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("商户签约管理失败！ e:{}", e.getMessage());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }


    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntSignInfoManageResponse mchntSignInfoManageResponse = (MchntSignInfoManageResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntSignInfoManageResponse);

    }

    /**
     * 签约信息-影像管理统一入口
     *
     * @param request 签约管理请求对象
     * @throws Exception 异常
     */
    private void manageSignImageInfo(MchntSignInfoManageRequest request) throws Exception {
        //处理影像信息
        List<SignImageInfoBean> signImageInfoBeanList = new ArrayList<>();
        if (null != request.getBusinessLicenceInfoBean().getSignImageInfoBean()
                && !StringUtil.isEmptyOrNull(request.getBusinessLicenceInfoBean().getSignImageInfoBean().getImageType())
                && !StringUtil.isEmptyOrNull(request.getBusinessLicenceInfoBean().getSignImageInfoBean().getImageLocalPath())) {
            signImageInfoBeanList.add(request.getBusinessLicenceInfoBean().getSignImageInfoBean());
        }
        if (null != request.getMchntArtifInfoBean().getCertFaceImage()
                && !StringUtil.isEmptyOrNull(request.getMchntArtifInfoBean().getCertFaceImage().getImageType())) {
            signImageInfoBeanList.add(request.getMchntArtifInfoBean().getCertFaceImage());
        }
        if (null != request.getMchntArtifInfoBean().getCertBackImage()
                && !StringUtil.isEmptyOrNull(request.getMchntArtifInfoBean().getCertBackImage().getImageType())) {
            signImageInfoBeanList.add(request.getMchntArtifInfoBean().getCertBackImage());
        }

        List<MchntImageInfoBean> mchntImageInfoBeanList = new ArrayList<>();
        for (SignImageInfoBean signImageInfoBean : signImageInfoBeanList) {
            MchntImageInfoBean mchntImageInfoBean = new MchntImageInfoBean();
            mchntImageInfoBean.setImageType(signImageInfoBean.getImageType());
            List<ImageInfoBean> imageInfoBeanList = new ArrayList<>();
            ImageInfoBean imageInfoBean = new ImageInfoBean();
            BeanUtil.beanCopy(signImageInfoBean, imageInfoBean);
            imageInfoBeanList.add(imageInfoBean);
            mchntImageInfoBean.setImageInfoList(imageInfoBeanList);
            mchntImageInfoBeanList.add(mchntImageInfoBean);
        }

        if (!CollectionUtils.isEmpty(signImageInfoBeanList)) {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            MchntBaseInfo mchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue(BompTreeNodeConstant.MCHNT_BASE_INFO, MchntBaseInfo.class);
            InitParamUtil.manageMchntImage(mchntBaseInfo, mchntImageInfoBeanList, ImageTypeEnum.SIGN_MANAGE_IMAGE_TYPES);
        }
    }
}
